package com.sunk.mybatis.mymybatis;

/**
 * @Author: Sunk 673116067@qq.com
 * @Date: 2018/10/10 14:38
 * @Description:
 */

import com.sunk.mybatis.mymybatis.Configuration.Function;
import com.sunk.mybatis.mymybatis.Configuration.MapperBean;
import com.sunk.mybatis.mymybatis.Configuration.MyConfiguration;
import com.sunk.mybatis.mymybatis.Configuration.SimpleSqlsession;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.List;

public class MyMapperProxy implements InvocationHandler{

    private  SimpleSqlsession mySqlsession;

    private MyConfiguration myConfiguration;

    public MyMapperProxy(MyConfiguration myConfiguration,SimpleSqlsession mySqlsession) {
        this.myConfiguration=myConfiguration;
        this.mySqlsession=mySqlsession;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

        MapperBean readMapper = myConfiguration.map.get(method.getDeclaringClass().getName());
        //是否是xml文件对应的接口
        if(!method.getDeclaringClass().getName().equals(readMapper.getInterfaceName())){
            return null;
        }
        List<Function> list = readMapper.getList();
        if(null != list || 0 != list.size()){
            for (Function function : list) {
                //id是否和接口方法名一样
                if(method.getName().equals(function.getFuncName())){
                    return mySqlsession.selectOne(function.getSql(), String.valueOf(args[0]));
                }
            }
        }
        return null;
    }
}
